import uuid from 'uuid/v4';
/**
 * 比较对象属性值，返回已改变的对象的属性值
 * @param  {any} obj    原对象
 * @param  {any} comparObj 比较对象
 * @return {any}        [description]
 */
export const comparisonValue = (obj: any, comparObj: any): any => {
  const newObj = {};
  Object.keys(obj).forEach((key) => {
    if (obj[key] !== comparObj[key] && obj[key] != null) {
      newObj[key] = obj[key];
    }
  });
  return newObj;
};

export const hasProperty = (obj: object, property: string): boolean => {
  return obj.hasOwnProperty(property);
};

export const normObject = (obj: object): any => {
  const newObj = {};
  Object.keys(obj).forEach((key) => {
    if (obj[key] !== null && obj[key] !== 'null') {
      newObj[key] = obj[key];
    }
  });
  return newObj;
};

/**
 * 判断类型是否符合
 * @param  obj  对象
 * @param  type 类型
 * 字符串 '[object String]'
 * 数字 '[object Number]'
 * 日期 '[object Date]'
 * 布尔 '[object Boolean]'
 * 对象 '[object Object]'
 * 数组 '[object Array]'
 * 函数 '[object Function]'
 * @return boolean
 */
export const callType = {
  call: (obj: any, type: string): boolean => {
    return Object.prototype.toString.call(obj) === type;
  },
  type: {
    string: '[object String]',
    number: '[object Number]',
    date: '[object Date]',
    boolean: '[object Boolean]',
    object: '[object Object]',
    array: '[object Array]',
    function: '[object Function]'
  }
};

export const messageFormat = (formatStr: string, ...str) => {
  return formatStr.replace(/\{(\d+)\}/g, (v) => {
    const idx = parseInt(v.replace(/\{/g, '').replace(/\}/g, ''), 10);
    return str[idx] ? str[idx] : v;
  });
};

// 笛卡尔积
export const cartesianProduct = (data: any) => {
  const len: number = data.length;
  if (len >= 2) {
    const len1 = data[0].length;
    const len2 = data[1].length;
    const newlen = len1 * len2;
    const temp = new Array(newlen);
    let index = 0;
    for (let i = 0; i < len1; i++) {
      for (let j = 0; j < len2; j++) {
        if (Array.isArray(data[0][i])) {
          temp[index] = [...data[0][i], data[1][j]];
        } else {
          temp[index] = [data[0][i], data[1][j]];
        }
        index++;
      }
    }
    const newArray = new Array(len - 1);
    for (let i = 2; i < len; i++) {
      newArray[i - 1] = data[i];
    }
    newArray[0] = temp;
    return cartesianProduct(newArray);
  } else {
    return data[0];
  }
};

export const getUUID = (): string => {
  return uuid().replace(new RegExp('-', 'gm'), '');
};
